/**
     * 
     */

package com.xyz.frame.sys.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.xyz.frame.bean.model.User;
import com.xyz.frame.security.common.bo.UserInfoInTokenBO;
import com.xyz.frame.security.common.util.AuthUserContext;
import com.xyz.frame.sys.dao.SysUserMapper;
import com.xyz.frame.sys.dao.SysUserRoleMapper;
import com.xyz.frame.sys.model.SysRole;
import com.xyz.frame.sys.model.SysUser;
import com.xyz.frame.sys.model.SysUserRole;
import com.xyz.frame.sys.service.SysRoleService;
import com.xyz.frame.sys.service.SysUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 系统用户
 * 
 */
@Service("sysUserService")
@AllArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

	private SysUserRoleMapper sysUserRoleMapper;

	private SysUserMapper sysUserMapper;

	private SysRoleService sysRoleService;


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveUserAndUserRole(SysUser user) {
		user.setCreateTime(new Date());
		sysUserMapper.insert(user);
		if(CollUtil.isEmpty(user.getRoleIdList())){
			return ;
		}
		//保存用户与角色关系
		sysUserRoleMapper.insertUserAndUserRole(user.getUserId(), user.getRoleIdList());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateUserAndUserRole(SysUser user) {
		// 更新用户
		sysUserMapper.updateById(user);

		//先删除用户与角色关系
		sysUserRoleMapper.deleteByUserId(user.getUserId());

		if(CollUtil.isEmpty(user.getRoleIdList())){
			return ;
		}
		//保存用户与角色关系
		sysUserRoleMapper.insertUserAndUserRole(user.getUserId(), user.getRoleIdList());
	}

	@Override
	public void updatePasswordByUserId(Long userId, String newPassword) {
        SysUser user = new SysUser();
        user.setPassword(newPassword);
        user.setUserId(userId);
        sysUserMapper.updateById(user);
    }

	@Override
	public void deleteBatch(Long[] userIds,Long shopId) {
		sysUserMapper.deleteBatch(userIds,shopId);
	}

	@Override
	public SysUser getByUserName(String username) {
		return sysUserMapper.selectByUsername(username);
	}

	@Override
	public SysUser getSysUserById(Long userId) {
		return sysUserMapper.selectById(userId);
	}

	@Override
	public List<String> queryAllPerms(Long userId) {
		return sysUserMapper.queryAllPerms(userId);
	}


	/**
	 * 根据用户名获取用户登录信息
	 *
	 * @return
	 */
	public Map<String, Object> getUserInfo() {
		Map<String, Object> result = new HashMap<>();

		//获取当前登录用户用户名
		UserInfoInTokenBO userInfoInTokenBO = AuthUserContext.get();

		SysUser user = this.getByUserName(userInfoInTokenBO.getUserName());
		if (null == user) {
			return Maps.newHashMap();
			//throw new GuliException(ResultCodeEnum.FETCH_USERINFO_ERROR);
		}
		LambdaQueryWrapper<SysUserRole> qwrUr = new LambdaQueryWrapper<>();
		qwrUr.eq(SysUserRole::getUserId, user.getUserId());
		List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(qwrUr);
		List<Long> roleIds = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
		//根据用户id获取角色
		LambdaQueryWrapper<SysRole> qwr = new LambdaQueryWrapper<>();
		qwr.in(SysRole::getRoleId, roleIds);
		List<SysRole> roleList = sysRoleService.list(qwr);
		List<String> roleNameList = roleList.stream().map(item -> item.getRoleName()).collect(Collectors.toList());
		if(roleNameList.size() == 0) {
			//前端框架必须返回一个角色，否则报错，如果没有角色，返回一个空角色
			roleNameList.add("");
		}

		//根据用户id获取操作权限值
//		List<String> permissionValueList = permissionService.selectPermissionValueByUserId(user.getId());
//		redisTemplate.opsForValue().set(username, permissionValueList);

		result.put("name", user.getUsername());
		result.put("avatar", "https://szy-education.oss-cn-shenzhen.aliyuncs.com/admin_head.jpg");
		result.put("roles", roleNameList);
		result.put("permissionValueList", userInfoInTokenBO.getPerms());
		return result;
	}
}
